﻿using System;
using System.Net;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WeiboPlus.Models;
using System.Diagnostics;
using System.Net.NetworkInformation;

namespace WeiboPlus.Service
{
    public class SNSPollingService : ISNSPollingService
    {
        IAccountManager _am;
        PollingConfiguration _config;
        Timer _timer;
        IStatusService _statusService;

        long sinceID;

        public long SinceID
        {
            get { return sinceID; }
            set { sinceID = value; }
        }

        public SNSPollingService(IAccountManager am, IStatusService statusService)
        {
            _am = am;
            _config = PollingConfiguration.Default;
            _statusService = statusService;
        }

        public void Start()
        {
            if (_timer == null)
                _timer = new Timer(Callback);
            //_timer.Change(_config.PollingInterval, _config.PollingInterval);
            _timer.Change(TimeSpan.FromMilliseconds(5000), _config.PollingInterval);
        }

        void Callback(object status)
        {
            var isAva = NetworkInterface.GetIsNetworkAvailable();

            if (!isAva)
                return;

            var request = new SNSRequest() { Type = SNSType.QueryCount };

            //request.Parameters.Add(new SNSParameter(SNSParametersConstants.WITH_STATUS, "1"));
            //request.Parameters.Add(new SNSParameter(SNSParametersConstants.SINCE_ID, SinceID + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TIME_STAMP, DateTime.Now.Ticks.ToString()));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.OP, "0"));
            if (OnPollingStarted != null)
                OnPollingStarted(this, null);
            _statusService.QueryCounts(request, (c, r) =>
            {
                if (!r.IsSuccess)
                {
                    Debug.WriteLine(r.Message);
                    //MessageBox.Show(r.Message);
                }
                else if (c != null)
                {
                    if (OnPollingCompleted != null)
                        OnPollingCompleted(this, new SNSPollingEventArgs(c));
                }
            });
        }

        public void Stop()
        {
            _timer.Change(0, Timeout.Infinite);
        }

        public event EventHandler<SNSPollingEventArgs> OnPollingCompleted;

        public event EventHandler<EventArgs> OnPollingStarted;

        public void Config(PollingConfiguration config)
        {
            _config = config;
        }
    }


}
